//
//  LocationAndObserver.m
//  GroupDeal
//
//  Created by lewang on 14-7-16.
//  Copyright (c) 2014年 groupdeal. All rights reserved.
//

#import "LocationAndObserver.h"
//#import <BaiduMapAPI/BMapKit.h>
#import "GeocodeShare.h"

#define PI                      3.1415926
#define EARTH_RADIUS            6378.137        //地球近似半径

static LocationAndObserver* sharedSingleton;

@implementation LocationAndObserver
{
    CLGeocoder  *geocoder_;
    NSInteger   times;//更新次数，多次更新会精确
}

- (id)init
{
    self = [super init];
    
    if(self)
    {
        _isGetLocation = NO;//是否已取得坐标
        _isGetGeoCode  = NO; //是否已经取得反地理
        
        geocoder_ = nil;
        
        times = 3;
        _FinalLocation = nil;
        _observers = [[NSMutableArray alloc] init];
        
        self.locationManager = [CLLocationManager new];
        [self.locationManager setDelegate:self];
        [self.locationManager setDistanceFilter:kCLDistanceFilterNone];
        [self.locationManager setHeadingFilter:kCLHeadingFilterNone];
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        
        
        //IOS8 的特殊处理
        if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            NSLog(@"ios 8 Authorization");
            [self.locationManager requestAlwaysAuthorization]; // 永久授权
//            [self.locationManager requestWhenInUseAuthorization]; //使用中授权
        }
    }
    
    return self;
}

-(void)UpdateLocation
{
     [self.locationManager startUpdatingLocation];
}

+ (LocationAndObserver*)sharedSingleton
{
    if(!sharedSingleton) {
        @synchronized(sharedSingleton) {
            sharedSingleton = [[LocationAndObserver alloc] init];
        }
    }
    
    return sharedSingleton;
}


#pragma mark - CLLocationManagerDelegate
-(void)ReverseGeocodeLocation
{
    // Reverse Geocoding
    if (!geocoder_) {
        geocoder_ = [[CLGeocoder alloc] init];
    }
     
    [geocoder_ reverseGeocodeLocation:_FinalLocation completionHandler:^(NSArray *placemarks, NSError *error)
     {
         if (error == nil && [placemarks count] > 0)
         {
             
             _isGetGeoCode = YES;
             _placemark = [placemarks lastObject];
             
             
             //存储存地理信息
             [[GeocodeShare sharedGecode] UpdataGecodeWithPlace:_placemark AndLocation:_FinalLocation];
             
             NSLog(@"%@ %@ %@ %@ %@ %@",
                   
                   _placemark.administrativeArea,
                   _placemark.locality,
                   _placemark.subLocality,
                   _placemark.thoroughfare,
                   _placemark.subThoroughfare,
                   _placemark.name);
             
             for (id<LocationObserver> observer in self.observers)
             {
                 if ([observer respondsToSelector:@selector(GeocodeLocation:)]) {
                     [observer GeocodeLocation:_placemark];
                 }
                 
             }
         }
         else
         {
             NSLog(@"%@", error.debugDescription);
         }
     }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
//    NSLog(@"didFailWithError: %@", error);
//    UIAlertView *errorAlert = [[UIAlertView alloc]
//                               initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//    [errorAlert show];
}



- (void)locationManager:(CLLocationManager *)manager
	 didUpdateLocations:(NSArray *)locations
{
    CLLocation *newLocation  = [locations lastObject];
    
    NSLog(@"didUpdateToLocation: (%f, %f)", newLocation.coordinate.longitude, newLocation.coordinate.latitude);
    
    if ((times - 1) > 0) {
        times -= 1;
        return;
    }
    
    
    CLLocation *currentLocation = newLocation;
    

    if (currentLocation != nil)
    {
        [_locationManager stopUpdatingLocation];
        
        
        //存储存地理信息
        [[GeocodeShare sharedGecode] UpdataGecodeWithLoca:currentLocation];
        
        _FinalLocation = newLocation;
        _isGetLocation = YES;
        
        
        NSLog(@"开始反地理");
        [self ReverseGeocodeLocation];
        
        
        for (id<LocationObserver> observer in self.observers) {
            if ([observer respondsToSelector:@selector(LocationDidChange:)]) {
                [observer LocationDidChange:newLocation];
            }
        }
        
        
        
    }
    
}

//谷歌地图SDK 反地理
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    /*
    NSLog(@"didUpdateToLocation: (%f, %f)", newLocation.coordinate.longitude, newLocation.coordinate.latitude);
    
    if ((times - 1) > 0) {
        times -= 1;
        return;
    }
    
    
    CLLocation *currentLocation = newLocation;
    if (currentLocation != nil)
    {
        [_locationManager stopUpdatingLocation];
        _FinalLocation = newLocation;
        _isGetLocation = YES;
        
        
        NSLog(@"开发反地理");
        [self ReverseGeocodeLocation];
        
        
        for (id<LocationObserver> observer in self.observers) {
            if ([observer respondsToSelector:@selector(LocationDidChange:)]) {
                [observer LocationDidChange:newLocation];
            }
        }
//        latLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
//        longLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
    }
    */
    // Stop Location Manager
   
}


//单位米
+(double )distanceLoca1:(CLLocationCoordinate2D)loca1 ToLoca2:(CLLocationCoordinate2D)loca2
{
    __block double blockDist = 0;
    dispatch_queue_t concurrentQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    
    dispatch_sync(concurrentQueue, ^{
    
        double radLat1 = loca1.latitude * PI / 180.0;
        double radLat2 = loca2.latitude * PI / 180.0;
        double a = radLat1 - radLat2;
        
        double b = (loca1.longitude * PI/180.0) - (loca2.longitude * PI/180.0);
        
        double dst = 2 * asin((sqrt(pow(sin(a / 2), 2) + cos(radLat1) * cos(radLat2) * pow(sin(b / 2), 2) )));
        
        dst = dst * EARTH_RADIUS;
        blockDist = round(dst * 10000) / 10000;
    
    });
   
    return blockDist;
}
@end
